package com.bee.web.security;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.Date;

import javax.crypto.Cipher;

/**
 * RSA非对称加密
 *
 * @author liuzy
 * @version 2015年5月22日
 */
public class RSA {
    private static PublicKey publicKey;
    private static PrivateKey privateKey;
    private static String publicKeyHexStr;

    public static String getPublicKey() {
        if (publicKey == null) {
            createKey();
        }
        return publicKeyHexStr;
    }

    static KeyPairGenerator keyPairGenerator = null;
    static KeyFactory kf = null;
    static Cipher cipher = null;

    static {
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            kf = KeyFactory.getInstance("RSA");
            cipher = Cipher.getInstance("RSA");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成服务器公钥和私钥
     *
     * @throws Exception
     */
    public static void createKey() {
        SecureRandom secureRandom = new SecureRandom(new Date().toString().getBytes());
        keyPairGenerator.initialize(1024, secureRandom);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        publicKey = keyPair.getPublic();
        privateKey = keyPair.getPrivate();
        publicKeyHexStr = Util.bytesToHexStr(publicKey.getEncoded());
        /* 输出到文件
		Util.outKeyFile(publicKey.getEncoded(), "d:/key/publicKey");
		Util.outKeyFile(privateKey.getEncoded(), "d:/key/privateKey");
		*/
    }

    /**
     * 公钥加密
     *
     * @param msg
     * @return
     */
    public static String encode(String msg) {
        try {
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] bytes = cipher.doFinal(msg.getBytes());
            return Util.bytesToHexStr(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 私钥解密
     *
     * @param hexMsg
     * @return
     */
    public static String decode(String hexMsg) {
        try {
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] bytes = cipher.doFinal(Util.hexStrToBytes(hexMsg));
            return new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
